package com.jzo2o.orders.manager.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.orders.dto.request.OrderCancelReqDTO;
import com.jzo2o.api.orders.dto.response.OrderResDTO;
import com.jzo2o.api.orders.dto.response.OrderSimpleResDTO;
import com.jzo2o.api.trade.RefundRecordApi;
import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.api.trade.enums.PayTypeEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.enums.EnableStatusEnum;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.orders.base.enums.OrderPayStatusEnum;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.dto.OrderSnapshotDTO;
import com.jzo2o.orders.manager.model.dto.response.OrdersPayResDTO;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

import static com.jzo2o.orders.base.constants.FieldConstants.SORT_BY;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-10
 */
@Slf4j
@Service
public class OrdersManagerServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersManagerService {

    @Autowired
    private RefundRecordApi refundRecordApi;

    @Override
    public List<Orders> batchQuery(List<Long> ids) {
        LambdaQueryWrapper<Orders> queryWrapper = Wrappers.<Orders>lambdaQuery().in(Orders::getId, ids).ge(Orders::getUserId, 0);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Orders queryById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 滚动分页查询
     *
     * @param currentUserId 当前用户id
     * @param ordersStatus  订单状态，0：待支付，100：派单中，200：待服务，300：服务中，400：待评价，500：订单完成，600：已取消，700：已关闭
     * @param sortBy        排序字段
     * @return 订单列表
     */
    @Override
    public List<OrderSimpleResDTO> consumerQueryList(Long currentUserId, Integer ordersStatus, Long sortBy) {
        //1.构件查询条件
        LambdaQueryWrapper<Orders> queryWrapper = Wrappers.<Orders>lambdaQuery()
                .eq(ObjectUtils.isNotNull(ordersStatus), Orders::getOrdersStatus, ordersStatus)
                .eq(Orders::getUserId, currentUserId);
        Page<Orders> queryPage = new Page<>();
        queryPage.addOrder(OrderItem.desc("create_time"));
        queryPage.setSearchCount(false);

        //2.查询订单列表
        Page<Orders> ordersPage = baseMapper.selectPage(queryPage, queryWrapper);
        List<Orders> records = ordersPage.getRecords();
        List<OrderSimpleResDTO> orderSimpleResDTOS = BeanUtil.copyToList(records, OrderSimpleResDTO.class);
        return orderSimpleResDTOS;

    }

    /**
     * 根据订单id查询
     *
     * @param id 订单id
     * @return 订单详情
     */
    @Override
    public OrderResDTO getDetail(Long id) {
        Orders orders = queryById(id);
        OrderResDTO orderResDTO = BeanUtil.toBean(orders, OrderResDTO.class);
        return orderResDTO;
    }

    /**
     * 订单评价
     *
     * @param ordersId 订单id
     */
    @Override
    @Transactional
    public void evaluationOrder(Long ordersId) {
//        //查询订单详情
//        Orders orders = queryById(ordersId);
//
//        //构建订单快照
//        OrderSnapshotDTO orderSnapshotDTO = OrderSnapshotDTO.builder()
//                .evaluationTime(LocalDateTime.now())
//                .build();
//
//        //订单状态变更
//        orderStateMachine.changeStatus(orders.getUserId(), orders.getId().toString(), OrderStatusChangeEventEnum.EVALUATE, orderSnapshotDTO);
    }

    /**
     * 取消订单
     *
     * @param reqDTO
     */
    @Override
    public void cancelOrder(OrderCancelReqDTO reqDTO) {
        // 1.先查询订单的支付状态,如果是已支付，则调用支付服务进行退款,没支付则直接取消
        Orders orders = queryById(reqDTO.getId());
        // 1.1 订单未支付
        if(orders.getOrdersStatus().equals(OrderStatusEnum.NO_PAY.getStatus())){
            log.info("订单未支付,直接取消");
            super.update(Wrappers.<Orders>lambdaUpdate()
                    .eq(Orders::getId, reqDTO.getId())
                    .set(StringUtils.hasText(reqDTO.getCancelReason()), Orders::getCancelReason, reqDTO.getCancelReason())
                    .set(Orders::getOrdersStatus, OrderStatusEnum.CANCELED.getStatus())
            );
        // 2.订单支付成功，且是还在分配中的订单,就调用支付服务进行退款
            //todo: 这里逻辑有问题
        } else if (orders.getPayStatus()== OrderPayStatusEnum.PAY_SUCCESS.getStatus() && orders.getOrdersStatus().equals(OrderStatusEnum.DISPATCHING.getStatus())) {
            log.info("取消订单开始执行,已经支付,第三支付服务开始退款");
            ExecutionResultResDTO executionResultResDTO = refundRecordApi.refundTrading(orders.getTradingOrderNo(), orders.getRealPayAmount());
            log.info("取消订单开始执行,第三支付服务开始退款,返回结果:{}", JSONUtil.toJsonStr(executionResultResDTO));
            //更新订单
            orders.setRefundNo(executionResultResDTO.getRefundNo());
            orders.setRefundStatus(executionResultResDTO.getRefundStatus());
            orders.setRefundId(executionResultResDTO.getRefundId());
            super.updateById(orders);
        }

    }
    /**
     * 查询定时任务取消未支付的订单
     * 15分钟前的订单
     * @param crateTime
     * @return
     */
    @Override
    public List<Orders> queryServeNoPayList(LocalDateTime crateTime) {
        log.info("================查询定时任务取消未支付的订单开始执行=================");
        List<Orders> list = super.list(Wrappers.<Orders>lambdaQuery()
                .eq(Orders::getOrdersStatus, OrderStatusEnum.NO_PAY.getStatus())
                .le(Orders::getCreateTime, crateTime));
        return list;
    }
    /**
     * 支付结果查询
     * @param id
     * @return
     */
    @Override
    public OrdersPayResDTO payResult(Long id) {
        log.info("支付结果开始查询");
        Orders orders = queryById(id);
        if (orders == null) {
            log.info("当前订单不存在：{}", id);
            return null;
        }
        OrdersPayResDTO ordersPayResDTO = new OrdersPayResDTO();
        ordersPayResDTO.setPayStatus(orders.getPayStatus());
        return ordersPayResDTO;
    }



}
